package cn.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Slf4j
public class TokenUtil {

    @Autowired
    public IntercepterConfig intercepterConfig;

    /**
     * 使用固定的解密秘钥
     */
    private static final String SECRET = "MARUIKAI1314";


    /**
     * 获取token
     *
     * @param id
     * ShopId
     * @return
     */
    public static String getToken( String id ,String ShopId) {
        //设置令牌的过期时间位 100 s
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 30);
        try {
            //用秘钥生成签名
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            String jwtToken = JWT.create()
                    .withClaim("id", id)
                    .withClaim("shopId", ShopId)
                    .withExpiresAt(instance.getTime()) //设置过期时间
                    .sign(algorithm);
            log.info("用户{}的token生成成功：{}", ShopId, jwtToken);
            return jwtToken;
        } catch (Exception e) {
            log.error("用户{}的token生成异常：{}", id, e);
            return null;
        }
    }

    /**
     * 验证
     *
     * @param token
     * @return
     */

    public static List<String> verify(String token) {
        try {
            // 根据用户信息userInfo生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            // 效验TOKEN
            verifier.verify(token);
            log.info("token：{}校验成功成功", token);
            //返回token内容
            return getTokenInfo(token);
        } catch (Exception exception) {
            log.error("token校验异常：{}", exception);
            return null;
        }
    }

    /**
     * 解析信息
     *
     * @param token
     * @return
     */
    private static List<String> getTokenInfo(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            ArrayList<String> list = new ArrayList<>();
            list.add(jwt.getClaim("userPhone").asString());
            list.add(jwt.getClaim("userId").asString());
            log.info("用户{}从token获取用户信息成功", list);
            return  list;
        } catch (JWTDecodeException e) {
            log.error("从token：{}获取用户信息异常：{}", token, e);
            return null;
        }
    }

}


